package cn.afactory.tygz.ui.fragments;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.harwkin.nb.camera.BaseImgView;
import com.harwkin.nb.camera.PageBigImageActivity;
import com.harwkin.nb.camera.model.PicsItem;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.R;
import cn.afactory.tygz.common.UserListType;
import cn.afactory.tygz.model.SnsCommentInfo;
import cn.afactory.tygz.model.SnsSubjectDetail;
import cn.afactory.tygz.model.SnsSubjectDetailList;
import cn.afactory.tygz.model.SnsTopicInfo;
import cn.afactory.tygz.ui.AppSettingsActivity;
import cn.afactory.tygz.ui.activities.TopicDetailActivity;
import cn.afactory.tygz.ui.base.adapter.NearByForumsAdapter;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshBase;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshListView;
import cn.afactory.tygz.ui.base.utils.DialogUtil;
import cn.afactory.tygz.ui.base.utils.ImageUtils;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.NaviUtils;
import cn.afactory.tygz.ui.base.utils.sns.TimeUtil;
import cn.afactory.tygz.ui.base.views.AutoGridView;
import cn.afactory.tygz.ui.sns.SubjectDetailActivity;
import cn.afactory.tygz.ui.sns.controller.SnsControler;

/**
 * Created by Kenneth on 15/9/24.
 */
public class TopicDetailFragment extends cn.afactory.tygz.ui.base.BaseFragment implements NearByForumsAdapter.OnItemClickListener{
    private final static int REQ_CODE_REFRESH_LIST = 0x1001;
    private SnsTopicInfo snsTopicInfo;
    private long mTopicId;
    private String mTopicTitle;

    private NearByForumsAdapter mAdapter;
    private List<SnsSubjectDetail> mList = new ArrayList<>();
    private SnsControler mController;

    private ImageView topicIcon;
    private TextView addFollow;
    private TextView subjectCount;
    private TextView commentCount;
    private TextView topicDes;
    private LinearLayout subjectAddLayout;

    private RelativeLayout channel_header_view;
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SnsControler.MSG_GET_TOPIC_DETAIL_OK:
                if (msg.obj instanceof SnsTopicInfo) {
                    SnsTopicInfo topic = (SnsTopicInfo)msg.obj;
                    if (null != topic) {
                        snsTopicInfo = topic;
                        initData();
                    }
                }
                break;
            case SnsControler.MSG_GET_TOPIC_DETAIL_KO:
                break;
            case SnsControler.MSG_GET_TOPIC_COMMENT_LIST_OK:
                if (msg.obj instanceof SnsSubjectDetailList) {
                    hideErrorPage(-1);
                    SnsSubjectDetailList t = (SnsSubjectDetailList) msg.obj;

                    if (t.rows != null && t.rows.size() >= 0) {
                        try {
                            if (msg.arg1 == SnsControler.MSG_DATA_FROM_CACHE && mAdapter.getCount() == 0 && mLastReqTime == 0) {
                                mList.addAll(t.rows);
                            } else {
                                if (mLastReqTime == 0) {
                                    mList.clear();
                                }
                                mList.addAll(t.rows);
                                mLastReqTime = t.rows.get(t.rows.size() - 1).addTime;
                            }
                            mAdapter.setData(mList);
                            mPageIndex = (mList.size()/mPageSize) + 1;
//                            setListListener();

                            if (plistview.isRefreshing()) {
                                plistview.onRefreshComplete();
                            }
                            if (t.rows.size() < mPageSize) {
                                plistview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            } else {
                                plistview.setMode(PullToRefreshBase.Mode.BOTH);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (mAdapter.getCount() == 0) {
                            showNullPage(true);
                        }
                    }
                }
                break;
            case SnsControler.MSG_GET_TOPIC_COMMENT_LIST_KO:
                if (mAdapter.getCount() == 0) {
                    hideErrorPage(-1);
                    showErrorPage(msg.arg1, new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            startLoadDatas();
                        }
                    });
                } else {
                    LocalUtils.showToast(mContext, "获取附近的动态失败！"/*StringUtil.handlerErrorCode(mContext, msg.arg1)*/);
                }
                break;
            case SnsControler.MSG_FOLLOWED_TOPIC_OK:
//                channel_header_view.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getArguments();
        if (null != bundle && bundle.containsKey(TopicDetailActivity.EXT_DATA_TAG)) {
            snsTopicInfo = (SnsTopicInfo)bundle.getSerializable(TopicDetailActivity.EXT_DATA_TAG);
        } else {
            snsTopicInfo = null;
        }

        if (null != bundle && bundle.containsKey(TopicDetailActivity.EXT_ID_TAG)) {
            mTopicId = bundle.getLong(TopicDetailActivity.EXT_ID_TAG);
        } else {
            mTopicId = 0;
        }

        if (null != bundle && bundle.containsKey(TopicDetailActivity.EXT_TITLE_TAG)) {
            mTopicTitle = bundle.getString(TopicDetailActivity.EXT_TITLE_TAG, null);
        } else {
            mTopicTitle = null;
        }

        mController = new SnsControler(getActivity().getApplicationContext(),mUIHandler,"NearByForums");
    }

    @Override
    public View onCreateViewCustom(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fg_channel_detail, null);
        initView(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        loadTopicDetailInfo();
    }
    //加载话题详情
    private void loadTopicDetailInfo(){
        if (null == snsTopicInfo) {
            mController.doLoadTopicDetailByTopicId(mTopicId);
        }else{
            mController.doLoadTopicDetailByTopicId(snsTopicInfo.topicId);
        }
    }

    private void initView(View view) {
        topicIcon = (ImageView)view.findViewById(R.id.channel_icon);
        addFollow = (TextView)view.findViewById(R.id.channel_add_follow);
        subjectCount = (TextView)view.findViewById(R.id.subject_count);
        commentCount = (TextView)view.findViewById(R.id.comment_count);
        topicDes = (TextView)view.findViewById(R.id.channel_des);
        subjectAddLayout = (LinearLayout)view.findViewById(R.id.nearby_forums_add);
        channel_header_view = (RelativeLayout)view.findViewById(R.id.channel_header_view);
        subjectAddLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NaviUtils.gotoPublishSubject(TopicDetailFragment.this,snsTopicInfo.topicName,snsTopicInfo.topicId,REQ_CODE_REFRESH_LIST);
            }
        });

        plistview = (PullToRefreshListView)view.findViewById(R.id.lv_subject_list);

        mAdapter = new NearByForumsAdapter(getActivity(),mList);
        mAdapter.setItemClickListener(this);
        plistview.setAdapter(mAdapter);

        plistview.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListView lv = plistview.getRefreshableView();
                if (position >= lv.getHeaderViewsCount()) {
                    position -= lv.getHeaderViewsCount();
                }
                SnsSubjectDetail snsSubjectDetail = (SnsSubjectDetail) mAdapter.getItem(position);
                Intent intent = new Intent(mContext, SubjectDetailActivity.class);
                intent.putExtra(SubjectDetailActivity.SUBJECT_DETAIL_TAG, snsSubjectDetail);
                startActivity(intent);
            }
        });

        plistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadDatas();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadSubjectData(false);
            }
        });
    }

    private void initData(){
        if (null != snsTopicInfo) {
            setTitleText(snsTopicInfo.topicName);
        }
        if(!((snsTopicInfo != null && snsTopicInfo.topicId == AppSettingsActivity.FEEDBACK_TOPIC_ID) ||
                (AppSettingsActivity.FEEDBACK_TOPIC_ID  == mTopicId)))  {
            setRightButton("关注的人", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    NaviUtils.gotoUserList(getActivity(),
                            -1,
                            "关注" + snsTopicInfo.topicName + "的用户",
                            snsTopicInfo.topicId,
                            -1,
                            UserListType.TOPIC_ATTENTION_USER_LIST);
                }
            });
        }

        addFollow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关注
                if (snsTopicInfo.isAttentioned) {
                    mController.doUnFollowTopic(addFollow, snsTopicInfo);
                } else {
                    mController.doFollowTopic(addFollow, snsTopicInfo);
                }
            }
        });

        String imageUrl = snsTopicInfo.topicIcon;
        if (!TextUtils.isEmpty(imageUrl)) {
            topicIcon.setScaleType(ImageView.ScaleType.CENTER_CROP);
            int nwidth = 60;
            BaseImgView.loadimg(topicIcon, ImageUtils.getThumbnailFullPath(imageUrl,
                            nwidth + "x" +
                                    nwidth),
                    R.drawable.ic_default_head_8,
                    R.drawable.ic_default_head_8,
                    R.drawable.ic_default_head_8,
                    ImageScaleType.EXACTLY,
                    nwidth,
                    nwidth, 0);
        } else {
            topicIcon.setImageResource(R.drawable.ic_default_head_8);
        }

        subjectCount.setText(snsTopicInfo.contents+"");
        commentCount.setText(snsTopicInfo.comments+"");

        if(snsTopicInfo.topicId == AppSettingsActivity.FEEDBACK_TOPIC_ID /*||
                SPUtils.isSelf(getActivity(),snsTopicInfo.userId)*/){
            addFollow.setVisibility(View.GONE);
            channel_header_view.setVisibility(View.GONE);
        }else{
            addFollow.setVisibility(View.VISIBLE);
            channel_header_view.setVisibility(View.VISIBLE);
            if (snsTopicInfo.isAttentioned) {
//                channel_header_view.setVisibility(View.GONE);
                addFollow.setText(getString(R.string.label_btn_cancel_attention));
            } else {
//                channel_header_view.setVisibility(View.VISIBLE);
                addFollow.setText(getString(R.string.label_btn_attention));
            }
        }

        if (!TextUtils.isEmpty(snsTopicInfo.desc)) {
            topicDes.setVisibility(View.VISIBLE);
            topicDes.setText(snsTopicInfo.desc);
        } else {
            topicDes.setText("");
            topicDes.setVisibility(View.GONE);
        }

        startLoadDatas();
    }

    private void startLoadDatas(){
        startLoadSubjectData(true);
    }

    /**
     * 加载listview数据
     */
    private int mPageIndex = 1;
    private int mPageSize = 10;
    private long mLastReqTime = System.currentTimeMillis();
    protected void startLoadSubjectData(boolean cleanData) {
        if (cleanData) {
            mPageIndex = 1;
            mLastReqTime = 0;
            mList.clear();
        }
        if(mTopicId > 0){
            mController.doGetCommentListByTopicId(mTopicId, mPageIndex, mPageSize);
        }else {
            mController.doGetCommentListByTopicId(snsTopicInfo.topicId, mPageIndex, mPageSize);
        }
    }

    @Override
    public void onPraise(TextView v, SnsSubjectDetail item) {
        if (TimeUtil.isFastDoubleClick()) {
            return;
        }
        if (item != null && item.id >= 0) {
            mController.doPraiseToSubject(v, item);
        }
    }

    @Override
    public void onPraise(AutoGridView autoGridView, TextView v, SnsSubjectDetail item) {
        if (TimeUtil.isFastDoubleClick()) {
            return;
        }
        if (item != null && item.id >= 0) {
            mController.doPraiseToSubject(autoGridView,v, item);
        }
    }

    @Override
    public void onClickImage(int position, List<String> mPath) {
        if (TimeUtil.isFastDoubleClick()) {
            return;
        }
        if (mPath != null) {
            ArrayList<PicsItem> list = new ArrayList<>();
            for (String tmp : mPath) {
                PicsItem picsItem = new PicsItem();
                picsItem.image = ImageUtils.getBigImageFullPath(tmp);
                list.add(picsItem);
            }
            NaviUtils.gotoViewBigImageActivity(getActivity(),list, position, false, false);
        }
    }

    @Override
    public void onClickTopic(String topic, long topicId) {
        NaviUtils.gotoTopicDetailActivity(mContext, topicId);
    }

    @Override
    public void onClickShare(SnsSubjectDetail item) {
        DialogUtil.showShareDialog(getActivity(), "分享Title",
                item.content,
                null,
                null,
                null,
                null,
                null,
                null);
    }

    @Override
    public void onClickIcon(SnsSubjectDetail item) {
        NaviUtils.gotoUserProfileActivity(getActivity(), item.userId, item.nickName);
    }

    @Override
    public void onClickCommentIcon(SnsCommentInfo commentInfo) {
        NaviUtils.gotoUserProfileActivity(getActivity(), commentInfo.userId, commentInfo.userName);
    }

    @Override
    public void onClickTextContent(SnsSubjectDetail item) {
        Intent intent = new Intent(mContext, SubjectDetailActivity.class);
        intent.putExtra(SubjectDetailActivity.SUBJECT_DETAIL_TAG, item);
        startActivity(intent);
    }

    @Override
    public void onClickSubjectList(String str) {

    }

    @Override
    public void onClickComment(SnsSubjectDetail item) {
        Intent intent = new Intent(mContext, SubjectDetailActivity.class);
        intent.putExtra(SubjectDetailActivity.SUBJECT_DETAIL_TAG, item);
        startActivity(intent);
    }

    @Override
    public void onClickCompany(SnsSubjectDetail item) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == Activity.RESULT_OK){
            if(requestCode == REQ_CODE_REFRESH_LIST){
                startLoadDatas();
            }
        }
    }
}
